package com.first.xiinn.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.first.core.web.Constants;
import com.first.core.web.action.BaseAction;
import com.first.xiinn.model.User;
import com.first.xiinn.service.UserService;
import com.opensymphony.xwork2.ActionContext;

public class LoginAction extends BaseAction{
	
	@Resource
	private UserService userService;
	public String login() {
		String msg = "";
		String success = "false";
		String login_id = ServletActionContext.getRequest().getParameter("login_id");
		String login_password = ServletActionContext.getRequest().getParameter("login_password");
		List<?> list=null;
		try {
			list = userService.loginSearch(login_id, null);
			if(list.isEmpty()){
				msg="用户名输入错误";
			}else if(list.size()>0){
				list =  userService.loginSearch(login_id, login_password);
				if(list.isEmpty()){
					msg="密码错误";
				}else{
					User user =(User) list.get(0);
					ActionContext ac = ActionContext.getContext();
					@SuppressWarnings("unchecked")
					Map<String, User> session = ac.getSession();
					session.put(Constants.USER_SESSION_KEY, user);
					success = "true";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg="系统错误";
		}finally{
			JSONObject json = new JSONObject();
			json.put("success",success);
			json.put("msg",msg);
			HttpServletResponse response =  ServletActionContext.getResponse();
			try {
				response.setHeader("Pragma","No-cache");
				response.setDateHeader("Expires",0);
				response.setHeader("Cache-Control","no-cache"); 
				response.setCharacterEncoding("UTF-8");
				PrintWriter write = response.getWriter();
				write.write(json.toString());
				write.flush();
				write.close();
			} catch (IOException e) {
				e.getMessage();
			}
		}
		return "success";
	}
}
